package com.example.administrator.biyesheji_print.Fragment;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.biyesheji_print.Adapter.mDocumenAdapter;
import com.example.administrator.biyesheji_print.Bean.PrintInfo;
import com.example.administrator.biyesheji_print.R;
import com.example.administrator.biyesheji_print.Utils.FileToMulti;
import com.example.administrator.biyesheji_print.Utils.PostRequest_Interface;
import com.example.administrator.biyesheji_print.Utils.ToJson;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/3/28.
 */

public class DocumentFragment extends Fragment implements View.OnClickListener {
    @BindView(R.id.bt_print)
    Button btPrint;
    Unbinder unbinder;
    private Realm realm;
    private ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
    private com.example.administrator.biyesheji_print.Adapter.mDocumenAdapter mDocumenAdapter;
    private View view;
    private View rootView;
    private RecyclerView rvPrint;
    private LinearLayoutManager linearLayoutManager;
    private ArrayList<File> mFileList;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }

        } else {
            view = inflater.inflate(R.layout.fragment_document, null);

        }
        mFileList=new ArrayList<File>();
        initView(view);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            realm = Realm.getDefaultInstance();
            initData();
            linearLayoutManager = new LinearLayoutManager(getContext());
            mDocumenAdapter = new mDocumenAdapter(list, getContext());
            mDocumenAdapter.setOnAdd(this);
            mDocumenAdapter.setOnSub(this);
            rvPrint.setLayoutManager(linearLayoutManager);
            rvPrint.setAdapter(mDocumenAdapter);
            mDocumenAdapter.setOnLongItemClickListener(new mDocumenAdapter.OnRecyclerViewLongItemClickListener() {
                @Override
                public void onItemLongClick(View view, int position) {
                    //Log.i("text","长按了");
                    showPopMenu(view,position);
                }
            });
        }
    }

    private void showPopMenu(View view, final int position) {
//        PopupMenu popupMenu = new PopupMenu(getContext(), view);
//        popupMenu.getMenuInflater().inflate(R.menu.menu_item,popupMenu.getMenu());
//        popupMenu.setGravity(Gravity.CENTER);
//        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                Log.i("text","删除；额");
//                return false;
//            }
//        });
//        popupMenu.show();
        View view1 = LayoutInflater.from(getContext()).inflate(R.layout.popwindow, null);
        final PopupWindow popupWindow = new PopupWindow(view1, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.showAsDropDown(view,500,-40);
        TextView tv_delete = view1.findViewById(R.id.tv_delete);
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("text",list.toString());
                String position1 = list.get(position).get("filepath").toString();
                String type = list.get(position).get("type").toString();
                final RealmResults<PrintInfo> position2 = realm.where(PrintInfo.class).equalTo("filepath", position1).equalTo("type",type).findAll();
                realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                       position2.deleteAllFromRealm();
                    }
                });
                popupWindow.dismiss();
                mDocumenAdapter.remove(position);
               // list.remove(position);

                //mDocumenAdapter.notifyDataSetChanged();

            }
        });

    }


    private void initData() {
        list.clear();
        RealmResults<PrintInfo> all = realm.where(PrintInfo.class).findAll();
        if (all.size() != 0) {
            for (int i = 0; i < all.size(); i++) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("filename", all.get(i).getFilename());
                map.put("filepath", all.get(i).getFilepath());
                map.put("type",all.get(i).getType());
                map.put("count","1");
                File file = new File(all.get(i).getFilepath());
                mFileList.add(file);
                list.add(map);
                // mDocumenAdapter.notifyDataSetChanged();
            }
        }


    }

    private void initView(View rootView) {
        Button bt_print = rootView.findViewById(R.id.bt_print);
        rvPrint = rootView.findViewById(R.id.rv_print);
//        DefaultItemAnimator animator = new DefaultItemAnimator();
//        //设置动画时间
//        animator.setAddDuration(2000);
//        animator.setRemoveDuration(2000);
//        rvPrint.setItemAnimator(animator);
        //Log.i("text",list.size()+"list.size()");

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ((ViewGroup) view.getParent()).removeView(view);
        }
        unbinder.unbind();
    }

    @OnClick(R.id.bt_print)
    public void onViewClicked() {
        Upload(mFileList);
    }

    private void Upload(ArrayList<File> mFileList) {
       Retrofit retrofit= new Retrofit.Builder()
               .baseUrl("http://knri.njit.edu.cn/printer/job/")
               .addConverterFactory(GsonConverterFactory.create())
              // .addConverterFactory()
               .build();
        MultipartBody body = FileToMulti.filesToMultipartBody(mFileList);
        PostRequest_Interface postRequest_interface = retrofit.create(PostRequest_Interface.class);
        Call<ToJson> call = postRequest_interface.uploadLoad(body);
        call.enqueue(new Callback<ToJson>() {
            @Override
            public void onResponse(Call<ToJson> call, Response<ToJson> response) {
                if (response.body().toString().equals("success")){
                    Toast.makeText(getContext(),"上传成功",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ToJson> call, Throwable t) {
                Toast.makeText(getContext(),"上传失败",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        Object tag = v.getTag();
        switch (v.getId()){
            case R.id.bt_add:
                if (tag!=null&&tag instanceof Integer){
                    int position = (Integer) tag;
                    int count = Integer.parseInt(list.get(position).get("count").toString());
                    count++;
                    list.get(position).put("count",count);
                    mDocumenAdapter.notifyDataSetChanged();
                }
                break;
            case R.id.bt_min:
                if (tag!=null&&tag instanceof Integer){
                    int position = (Integer) tag;
                    int count = Integer.parseInt(list.get(position).get("count").toString());
                    if (count>1){
                        count--;
                        list.get(position).put("count",count);
                        mDocumenAdapter.notifyDataSetChanged();
                    }

                }
                break;
        }
    }
}
